﻿using System;
using System.Web.UI.WebControls;
using ChapterX.BusinessFacade;
using ChapterX.Common;
using ChapterX.Data;
using ChapterX.Data.BooksDSTableAdapters;
using ChapterX.Data.CoursesDSTableAdapters;
using System.Data;

namespace ChapterX.Modules
{
    public partial class CourseEntryModule : ChapterX.Model.ModuleBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindRadioButtonLists();

                if (Utils.HasValue(Request.QueryString[QueryKeys.COURSE_ID]))
                {
                    Field_CourseId.Value = Utils.GetValue(Request.QueryString[QueryKeys.COURSE_ID]);
                    Delete.Visible = true;
                }
                else
                {
                    Field_CourseId.Value = String.Empty;
                    Delete.Visible = false;
                }

                if (CurrentUserInfo.IsTeacher)
                {
                    Row_TeacherId.Visible = false;
                }

                BindCourse();


                BindUnBoundBookList();
            }
        }

        protected void BindRadioButtonLists()
        {
            Field_Audience.Items.Clear();
            Field_Audience.Items.Add(new ListItem("未选择", "N/A"));
            Field_Audience.Items.Add(new ListItem("本科生", "本科生"));
            Field_Audience.Items.Add(new ListItem("研究生", "研究生"));
            Field_Audience.SelectedIndex = 0;
        }

        protected void BindCourse()
        {
            int courseId;

            if (Utils.HasValue(Field_CourseId.Value) && Int32.TryParse(Field_CourseId.Value, out courseId))
            {
                try
                {
                    CoursesTableAdapter adapter = new CoursesTableAdapter();
                    CoursesDS.CoursesRow course = adapter.GetCourseByCourseId(courseId)[0];

                    if (null == course)
                    {
                        throw new RecordNotExistedException();
                    }

                    Field_CourseNumber.Text = course.CourseNumber;
                    Field_CourseName.Text = course.CourseName;
                    if (!course.IsDepartmentNull())
                    {
                        Field_Department.Text = course.Department;
                    }
                    if (!course.IsSemesterNull())
                    {
                        Field_Semester.Text = course.Semester;
                    }
                    if (!course.IsAudienceNull())
                    {
                        Field_Audience.Text = course.Audience;
                    }
                    if (!course.IsCreditNull())
                    {
                        Field_Credit.Text = course.Credit.ToString();
                    }
                    if (!course.IsAssessmentNull())
                    {
                        Field_Assessment.Text = course.Assessment;
                    }
                    if (!course.IsVolumeNull())
                    {
                        Field_Volume.Text = course.Volume.ToString();
                    }
                    Field_TeacherId.Text = course.TeacherId;
                }
                catch (Exception ex)
                {
                    SetErrorMessage(ex.Message);
                    Logger.Log(ex);
                }
            }
            else
            {
                if (CurrentUserInfo.IsTeacher)
                {
                    Field_TeacherId.Text = CurrentUserInfo.Username;
                }
            }
        }


        protected void BindCourseBook()
        {
            CourseBookViewTableAdapter adapter = new CourseBookViewTableAdapter();
        }

        protected void Submit_Click(object sender, EventArgs e)
        {
            try
            {
                bool result = false;
                CourseSystem cs = new CourseSystem();
                CoursesDS.CoursesRow course = cs.CourseSchema.NewCoursesRow();

                if (Utils.HasValue(Field_CourseId.Value))
                {
                    try
                    {
                        course.CourseId = Int32.Parse(Utils.GetValue(Field_CourseId.Value));
                    }
                    catch
                    {
                        throw new UnexpectedException();
                    }
                }
                else
                {
                    course.CourseId = -1;
                }

                course.CourseNumber = Field_CourseNumber.Text;
                course.CourseName = Field_CourseName.Text;
                course.Department = Field_Department.Text;
                course.Semester = Field_Semester.Text;
                course.Audience = Field_Audience.Text;
                if (Utils.HasValue(Field_Credit.Text))
                {
                    try
                    {
                        course.Credit = Utils.ParseInt32(Utils.GetValue(Field_Credit.Text), 0);
                    }
                    catch
                    {
                        throw new InvalidInputException("字段值无效：课程学分");
                    }
                }
                course.Assessment = Field_Assessment.Text;
                if (Utils.HasValue(Field_Volume.Text))
                {
                    try
                    {
                        course.Volume = Utils.ParseInt32(Utils.GetValue(Field_Volume.Text), 0);
                    }
                    catch
                    {
                        throw new InvalidInputException("字段值无效：计划人数");
                    }
                }
                course.TeacherId = Field_TeacherId.Text;

                result = cs.SubmitCourse(course, CurrentUserInfo.Username);

                if (result)
                {
                    SetInfoMessage("课程信息提交成功。");
                    BindCourse();
                }
                else
                {
                    SetErrorMessage("课程信息提交失败。");
                }
            }
            catch (Exception ex)
            {
                SetErrorMessage(ex.Message);
                Logger.Log(ex);
            }
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            try
            {
                bool result = false;
                CourseSystem cs = new CourseSystem();

                result = cs.DeleteCourse(Int32.Parse(Field_CourseId.Value));

                if (result)
                {
                    SetInfoMessage("课程信息删除成功。");
                }
                else
                {
                    SetErrorMessage("课程信息删除失败。");
                }
            }
            catch (Exception ex)
            {
                SetErrorMessage(ex.Message);
                Logger.Log(ex);
            }
        }

        protected void BindUnBoundBookList()
        {
            //temp，假设当前用户为teacher，根据teacherid拉取书
            try
            {
                TeacherBookViewTableAdapter adpater = new TeacherBookViewTableAdapter();
                DataTable bookList = null;

                if (CurrentUserInfo.IsLibrarian)
                {
                    bookList = adpater.GetData();
                }
                else if (CurrentUserInfo.IsTeacher)
                {
                    bookList = adpater.GetBookListByTeacherId(CurrentUserInfo.Username);
                }
                else
                {
                    throw new UnexpectedException();
                }

                this.UnboundBookList.DataSource = bookList.DefaultView;
                this.UnboundBookList.DataValueField = "BookId";
                this.UnboundBookList.DataTextField = "Title";
                this.UnboundBookList.DataBind();
            }
            catch (Exception ex)
            {
                SetErrorMessage("数据绑定失败。");
                Logger.Log(ex);
            }
        }

        protected void BindBook_Click(object sender, EventArgs e)
        {
            try
            {
                bool result = false;
                CourseSystem cs = new CourseSystem();

                result = cs.BindCourseBook(Int32.Parse(Field_CourseId.Value),
                    Int32.Parse(this.UnboundBookList.SelectedValue), "教材");

                if (result)
                {
                    SetInfoMessage("教材绑定成功。");

                }
                else
                {
                    SetErrorMessage("教材绑定失败。");
                }
            }
            catch (Exception ex)
            {
                SetErrorMessage("教材绑定失败。");
                Logger.Log(ex);
            }
        }
    }
}